<?php
use Zend\Mail\Transport\Smtp as SmtpTransport;
use Zend\Mail\Transport\SmtpOptions;
Yii::setPathOfAlias('Zend',Yii::getPathOfAlias('application.vendor.Zend'));
class DefaultController extends Controller
{
    public function filters()
    {
        return array(
            'accessControl', // perform access control for CRUD operations
            'postOnly + delete', // we only allow deletion via POST request
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules()
    {
        return array(
            array('allow',  // allow all users to perform 'index' and 'view' actions
                'actions'=>array('index','show', 'create', 'captcha'),
                'users'=>array('*'),
            ),
        );
    }

	public function actionIndex()
	{
		$this->render('index');
	}

    public function actionShowOrder(){
 

		$this->render('show');
    }

    public function actionCreateOrder(){
		
		$cart_array = array();
        $cart_array = CartFunctions::getCartArray();
		if (is_array($cart_array) && count($cart_array)){
			$products = Product::model()->findAllByAttributes(array(
				'id'=>array_keys($cart_array),
			), array(
				'order'=>'title'
			));

            $model = new Order;

			if (isset($_POST['Order'])){
				$model->attributes = $_POST['Order'];
				$model->hash = sha1($model->username.$model->email.$model->phone.time());

                if ($model->save()){

                    $mailList = "<table>";
                    $totalPrice = 0;
                    CartFunctions::emptyCart();
					foreach ($products as $product) {
						OrderProduct::model()->addProduct($model->id, $product->id, $cart_array[$product->id]);
                        $totalPrice += $cart_array[$product->id]*$product->price;
                        $mailList .= "<tr>".
                            "<td>".
                            $product->title.
                            "</td>".
                            "<td>".
                            $product->price.
                            "</td>".
                            "</tr>";

					}
                    $mailList .= "<tr>".
                        "<td>".
                        "<b>Итого:</b>".
                        "</td>".
                        "<td><b>".
                        $totalPrice.
                        "</b></td>".
                        "</tr>";
                    $mailList .= "</table>";
                    $mail = new Zend\Mail\Message();
                    $mail->setEncoding("utf-8");
                    $mail->getHeaders()->addHeaderLine('Content-Type', 'text/html; charset=utf-8');

                    $mail->setBody('Имя: ' . $model->username . '. Телефон: ' . $model->phone . '. Email: ' . $model->email . '. Адрес: ' . $model->address . '<br/>' . $mailList . '<br/>Комментарий: ' . $model->comment);
                    $mail->setFrom('admin@bee-bee.by', 'Администратор');
                    $mail->addTo('bee-bee.by@mail.ru');
                    $mail->setSubject('Новый заказ');

                    $transport = new SmtpTransport();

                    $options   = new SmtpOptions(array(
                        'host'              => '193.232.92.14',
                        'port'              =>'25',
                        'connection_class'  => 'login',
                        'connection_config' => array(
                            'username' => 'admin@bee-bee.by',
                            'password' => 'UbtFXBEt1ynL',
                        ),
                    ));
                    $transport->setOptions($options);
                    $transport->send($mail);

					$this->redirect(array('showOrder'));
				}
			}

            $this->render('create', array(
                'cart'=>$cart_array,
                'model'=>$model,
                'products'=>$products
            ));
		} else {
			$this->redirect('/korzina');
		}
    }

    /**
     * Performs the AJAX validation.
     * @param Order $model the model to be validated
     */
    protected function performAjaxValidation($model)
    {
        if(isset($_POST['ajax']) && $_POST['ajax']==='order-form')
        {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

    public function loadModel($id)
    {
        $model=Order::model()->findByPk($id);
        if($model===null)
            throw new CHttpException(404,'The requested page does not exist.');
        return $model;
    }

    public function actions(){
        return array(
            'captcha'=>array(
                'class'=>'CCaptchaAction',
            ),
        );
    }
}
